package cn.edu.nuc.onlinestore.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import cn.edu.nuc.onlinestore.vo.Goods;
import cn.edu.nuc.onlinestore.vo.Person;

public class Acceptutil_2 extends Thread {

    boolean t=false;
	public void run() {
		 
		ServerSocket server = null;
		try {
			server = new ServerSocket(9002);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		while( true ){
			synchronized (this) {

				try{
				Socket client = server.accept();
				OutputStream out ;
				DataOutputStream dout;
				InputStream in = client.getInputStream();
				ObjectInputStream dis = new ObjectInputStream(in);
			
				List<Goods> list=(List<Goods>) dis.readObject();
				List<Goods> list2=getList();
				for(int i=0;i<list.size();i++){
					for(int b=0;b<list2.size();b++){
						if(list.get(i).getName().equals(list2.get(b).getName())){
							list2.get(b).setNum(list2.get(b).getNum()-list.get(i).getNum());
						}
					}
				}
				
					for(int c=0;c<list2.size();c++){
						File f=new File("D:/store/goods/"+list2.get(c).getName()+".db");
						GoodsUpdateutil gu=new GoodsUpdateutil();
						t=gu.ObjectUtil_b(f,list2.get(c));
					
					}
					
				if(t){
					out = client.getOutputStream();
					dout = new DataOutputStream(out);
					dout.writeBoolean(true);
					
					out.close();
					dout.close();
					client.close();
				}	
				}catch (IOException | ClassNotFoundException e) {
				// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}

	private List<Goods> getList() {
		File f=new File("D:\\store\\goods\\");
		File[] f1=f.listFiles();
		List<Goods> list3=new ArrayList<Goods>();
		for(int i=0;i<f1.length;i++){
			GoodsUpdateutil gu=new GoodsUpdateutil();
			Goods g=gu.ObjectUtil_a(f1[i]);
			list3.add(g);
		}
		
		return list3;
	}
}
